package com.sany.taskmanager.ui.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.sany.taskmanager.R;
import com.sany.taskmanager.bean.ColorBean;
import com.sany.taskmanager.databinding.ItemColorBinding;
import com.sany.taskmanager.util.EditUtil;

import java.util.List;

public class ColorAdapter extends RecyclerView.Adapter<ColorAdapter.VH> {

    private final Context mContext;
    private List<ColorBean> colorList;
    private OnSelectItem mOnSelectItem;

    public ColorAdapter(Context context) {
        mContext = context;
    }

    public void setList(List<ColorBean> colorList, OnSelectItem onSelectItem) {
        this.colorList = colorList;
        mOnSelectItem = onSelectItem;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemColorBinding itemColorBinding = ItemColorBinding.inflate(LayoutInflater.from(mContext), parent, false);
        return new VH(itemColorBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        ColorBean item = colorList.get(position);
        holder.llContainer.setBackgroundColor(Color.parseColor(item.getColorValue()));
        if (TextUtils.isEmpty(item.getColorName())){
            holder.tvColor.setText(item.getColorCode());
        } else {
            holder.tvColor.setText(item.getColorName());
        }
        boolean isDarkColor = EditUtil.isDarkColor(item.getColorValue());
        if (isDarkColor) {
            holder.tvColor.setTextColor(ContextCompat.getColor(mContext, R.color.white));
        } else {
            holder.tvColor.setTextColor(ContextCompat.getColor(mContext, R.color.black));
        }
        holder.itemView.setOnClickListener(v -> {
            if (mOnSelectItem != null) {
                mOnSelectItem.selectItem(item);
            }
        });
    }

    @Override
    public int getItemCount() {
        return colorList == null ? 0 : colorList.size();
    }

    static class VH extends RecyclerView.ViewHolder {
        public ViewGroup llContainer;
        public TextView tvColor;

        public VH(@NonNull ItemColorBinding itemColorBinding) {
            super(itemColorBinding.getRoot());
            llContainer = itemColorBinding.llContainer;
            tvColor = itemColorBinding.tvColor;
        }
    }

    public interface OnSelectItem {
        void selectItem(ColorBean colorBean);
    }
}
